import axios from 'axios'
import store from '@/store/index';
import router from '../router';
import { API } from '../api/api';

// 创建axios实例
const service = axios.create({
    baseURL: API.domain, // axios中请求配置有baseURL选项，表示请求URL公共部分
    headers: API.headers,
    timeout: 10000 // 超时
})
// request拦截器
service.interceptors.request.use(config => {
    config.headers['uid'] = store.getters['user/uid'];
    config.headers['token'] = store.getters['user/token'];
    return config;
}, error => {
    console.log(error);
    Promise.reject(error);
})

// 响应拦截器
service.interceptors.response.use(
    res => {
        if (res.data.code == 'error') {//请求失败
            if (res.data.message.indexOf("Exception") > -1) {// 异常
                // Message({
                //     message: res.data.message,
                //     type: 'error',
                //     duration: 3 * 1000
                // });
            } else if (res.data.message.indexOf("permission") > -1) {//没有权限
                store.commit("user/uid", "");
                store.commit("user/token", "");
                store.commit("user/name", "");
                router.push({ path: "/login", query: { redirect: "" } });
                res.data.message = res.data.message.replace("permission", "");
            }
            // Message({
            //     message: res.data.message,
            //     type: 'warning',
            //     duration: 3 * 1000
            // });
        } else { //请求成功
            if (res.data.message != null && res.data.message != "") {
                // Message({
                //     message: res.data.message,
                //     type: 'success',
                //     duration: 1000
                // })
            }
        }
        return res.data;
    },
    error => {
        console.log('err-->' + error)
        let { message } = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        }
        else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        }
        else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        // Message({
        //     message: message,
        //     type: 'error',
        //     duration: 3 * 1000
        // })
        return Promise.reject(error);
    }
)

export default service
